package com.zero.service;

import com.zero.entity.Admin;
import com.zero.mapper.AdminMapper;
import com.zero.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    public Result getAdminInfo(HttpServletRequest request) {
        Admin admin = (Admin) request.getAttribute("admin");
        if (admin == null && admin.getId() == null)
            return Result.fail("获取不到用户信息");
        admin = adminMapper.selectById(admin.getId());

        return Result.ok("获取管理员信息成功", admin);
    }

    /**
     * 验证管理员密码
     * @param password
     * @param request
     * @return
     */
    public Result verifyPassword(String password, HttpServletRequest request) {
        Admin admin = (Admin) request.getAttribute("admin");
        if (admin == null || admin.getId() == null)
            return Result.fail("获取不到管理员信息");
        admin = adminMapper.selectById(admin.getId());
        if (admin != null && admin.getPassword().equals(password))
            return Result.ok("验证通过");
        return Result.fail("验证不通过");
    }

    public Result updatePassword(Map map, HttpServletRequest request) {

        String newPassword = (String) map.get("newPassword");
        if (newPassword == null || newPassword.equals(""))
            return Result.fail("获取不到新密码");

        Admin admin = (Admin) request.getAttribute("admin");
        if (admin == null || admin.getId() == null)
            return Result.fail("获取不到管理员信息");
        Admin newInfo = new Admin();
        newInfo.setId(admin.getId());
        newInfo.setPassword(newPassword);
        int row = adminMapper.update(newInfo);
        if(row == 1)
            return Result.ok("修改密码成功");
        return Result.fail("修改密码失败");

    }
}
